<template>
	<view>
		<uni-popup ref="tipsRef" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="duration"></uni-popup-message>
		</uni-popup>
		<MyModal :openModalFlag="modalWXLoginFlag" :okFun="mpGetUserInfo">
			<template #title>
				点击确认授权微信登录
			</template>
		</MyModal>
		<MyModal :openModalFlag="protocolData.needAuthorization">
			<template #title>
				个人信息保护指引
			</template>
			<template #content>
				<view class="protocol_box">
					在您使用【有爱宿舍】服务之前，请仔细阅读
					<text class="protocol_name_url" @click="()=>goGetPrivacyInfo()">
						{{protocolData.title}}
					</text>
					。如果您同意{{protocolData.title}}，请点击“同意“开始使用【有爱宿舍】。
				</view>
			</template>
			<template #okCancelBtn>
				<view class="btn_box_solt">
					<button type="default" class="protocol_cancel" @click="()=>handleRefulePrivacy()">
						拒绝
					</button>
					<button id="agree-btn" style="font-size: 34rpx;" class="get_key_phone" open-type="agreePrivacyAuthorization"
						@agreeprivacyauthorization="()=>handleAgreePrivacyAuthorization()">同意</button> 		
				</view>
			</template>
		</MyModal>
		<MyModal :openModalFlag="modelIsShowViewAdFlag" :okFun="okViewAdVideoFun" :cancelFun="cancelViewAdVideoFun">
			<template #title>
				观看15秒广告获取2次{{showIsViewAdTaskName}}机会
			</template>
		</MyModal>
		<MyModal :openModalFlag="modalAuthMessageFlag" :okFun="viewedAuthMessageFun" :cancelFun="viewedAuthMessageFun">
			<template #title>
				建议您点击总是保持选择，方便收到提醒
			</template>
			<template #content>
				<MyNull img="suggestMessage.jpg"></MyNull>
			</template>
		</MyModal>
		<MyModal :openModalFlag="openPhonePopubFlag" :cancelFun="viewedAuthMessageFun">
			<template #title>
				<view style="text-align: center;">
					{{noBindPhone ? "绑定手机号" : "解绑手机号"}}
				</view>
				<view v-if="noBindPhone" style="text-align: center;">
					{{tipConent}}
				</view>
			</template>
			<template #content>
				<MyNull img="bindPhone.png"></MyNull>
			</template>
			<template #okCancelBtn>
				<view class="btn_box_solt">
					<button type="default" class="get_key_phone get_key_phone_cancel" @click="()=>openPhonePopubFlag = -Math.random()">
						关闭
					</button>
					<button v-if="noBindPhone" type="default" class="get_key_phone" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">
						授权获取手机号					
					</button>
					<button v-else type="default" @click="()=>unBindPhoneFun()" class="get_key_phone">
						解绑当前手机号				
					</button>
				</view>
			</template>
		</MyModal>
	</view>
</template>

<script setup>
	/**
	 * 全局的操作与提示
	 */
	import { onHide , onShow,onUnload,onLoad} from '@dcloudio/uni-app'
	import { ref,reactive,onMounted,onBeforeUnmount, nextTick,computed, onUnmounted} from "vue"
	
	import moment from 'moment'	
	
	import {userStore} from '@/stores/user'
	import {dynamicStyleStore} from '@/stores/dynamicStyle.js'
	
	import {UserModel} from '@/service/model/user.js'
	
	import MyNull from '@/components/MyNull/MyNull.vue'
	import MyButton from '@/components/MyButton/MyButton.vue'
	
	import {
		changeDate
	} from '@/utils/changeData'
	
	import {
		UserIsJoinActiveByNewUser,
		DefaultPhone
	} from '@/enum/GlobalEnum.js'
	
	import {
		verifyIsLastOpenPhone
	} from '@/hooks/verify.js'
	
	const user_store=userStore()
	const dynamicStyle_store = dynamicStyleStore()
	
	const userModel = new UserModel()
	
	const tipsRef = ref()
	const messageText= ref('')
	const duration = ref()
	const msgType = ref('')
	const modalWXLoginFlag=ref(0)
	const modalAuthMessageFlag=ref(0)
	const openPhonePopubFlag=ref(0)
	const bindPhoneCallback=ref(false)
	const tipConent = ref('')
	const taskVideoAd=ref(null)
	const pushScreenAd=ref(null)
	const modelIsShowViewAdFlag=ref(0)
	const taskOkCallback=ref(null)
	const showIsViewAdTaskName=ref('')
	const isAllowShowPushScreenAd=ref(false)
	const nowPage = ref('')
	const protocolData=ref({
		title:'',
		needAuthorization: -1,
		callback:null
	})
	
	const noBindPhone = computed(()=>user_store.userInfo.phone === DefaultPhone)
	
	const {
		primary_light_color,
		primary_text_color,
		primary_orther_color,
		primary_hot_color,
		primary_cool_color
	} = dynamicStyle_store.dormitoryStyle
	
	//展示提示
	const tipsCallback=(msg,type='success',durationNum=1500)=>{
		msgType.value = type
		messageText.value = msg
		duration.value = durationNum
		
		nextTick(()=>{
			tipsRef.value?.open && tipsRef.value.open()
		})
	}
	
	//设置pina的用户信息(用于js文件无法使用pina的问题)
	const setUserStore=(data)=>{
		user_store.setUserInfo(data)
	}
	
	const getPages=(isFromNormal)=>{
		if(isFromNormal) return
		const pages=getCurrentPages()
		const nowFullPath=pages[pages.length-1].$page.fullPath
		const tabPages=[
			'/pages/Dormitory/Dormitory',
			'/pages/Dormitorys/Dormitorys',
			'/pages/User/User'
		]
		if(tabPages.indexOf(nowFullPath)!==-1){
			return
		}else{
			uni.redirectTo({
				url:nowFullPath
			})
		}
	}
	
	//激活宣传大使发起的活动
	const joinPublicityActice=async(publicity_id)=>{
		const {data,success} = await userModel.postJoinPublicity({},publicity_id)
		uni.removeStorageSync('newUserActive')
		if(success){
			uni.$emit('tips',data,'success',3000)
		}
	}
	
	//解绑手机号
	const unBindPhoneFun=async()=>{
		const {data,success} = await userModel.patchUnBindPhone({})
		if(success){
			uni.$emit('tips',data,'success')
			openPhonePopubFlag.value = -Math.random()
		}
		getUserInfo()
	}
	
	//获取用户信息
	const getUserInfo = async (isFromNormal=false)=>{
		const {data,success} = await userModel.getUserInfo()
		if(success){
			data.createAt = changeDate(data.createAt)
			uni.$emit('userStore',data)
			
			const newUserActiveId = uni.getStorageSync('newUserActive')
			//证明没有参与过新用户活动，并且有一个新用户活动待用户激活
			if(
				data.isJoinActiveByNewUser === UserIsJoinActiveByNewUser.NO
				&& newUserActiveId?.publicity_id
			){
				joinPublicityActice(newUserActiveId.publicity_id)
			}else if(newUserActiveId?.publicity_id){
				uni.$emit('tips','您已经不是新用户了','info',2000)
				uni.removeStorageSync('newUserActive')
			}
			
			getPages(isFromNormal)
		}
	}
	
	//确认已读消息推送授权提示
	const handleCallback=ref()
	const viewedAuthMessageFun=()=>{
		handleCallback.value()
	}
	
	//微信登录
	const mpGetUserInfo = async() => {
		uni.login({
			async success(response) {
				uni.showLoading({
					title:'正在登录',
					mask:true
				})
				const {
					success: resultSuccess,
					data: resultData
				} = await userModel.postLoginByWX({
					code: response.code
				})
				if (resultSuccess) {
					if (resultData.isOldUser) { //老用户
						uni.setStorageSync('token', resultData.data)
						uni.$emit('tips', '登录成功', 'success')
					} else { //新用户
						uni.$emit('tips', '登录成功,建议您去修改个人信息', 'success')
						uni.setStorageSync('token', resultData.data)
					}
					uni.hideLoading()
					getUserInfo()
				} else {
					uni.$emit('tips', resultData, 'error')
				}
			}
		})
	}
	
	//授权手机号
	const decryptPhoneNumber=async(v)=>{
		if(!noBindPhone.value){
			const format = 'YYYY-MM-DD'
			//一天只能换绑两次手机号
			const isTodayChangeBindPhone = 
				uni.getStorageSync('isTodayChangeBindPhone')
				|| {
					date:moment().format(format),
					count:0
				}
			if(isTodayChangeBindPhone.date === moment().format(format)){
				if(isTodayChangeBindPhone.count >= 2){
					uni.$emit('tips','每天只能换绑两次手机号','warn',2000)
					openPhonePopubFlag.value = -Math.random()
					return
				}else{
					isTodayChangeBindPhone.count++
					uni.setStorageSync('isTodayChangeBindPhone',isTodayChangeBindPhone)
				}
			}else{
				isTodayChangeBindPhone.date = moment().format(format)
				isTodayChangeBindPhone.count = 1
				uni.setStorageSync('isTodayChangeBindPhone',isTodayChangeBindPhone)
			}
		}
		const {code} = v.detail
		if(!code){
			// uni.$emit('tips','请添加手机号,方便收到通知','warn')
		}else{
			const {data,success}=await userModel.getPhoneNum({code})
			if(success){
				uni.$emit('tips',data,'success')
				openPhonePopubFlag.value = -Math.random()
				setTimeout(()=>{
					getUserInfo(true)
					bindPhoneCallback.value && (bindPhoneCallback.value)()
					bindPhoneCallback.value = false
				},1000)
			}
		}
	}
	const openAuthMessageTipFun=(e)=>{
		handleCallback.value=e
		modalAuthMessageFlag.value=Math.random()
	}
	const openWxLoginModelFun=()=>{
		modalWXLoginFlag.value=Math.random()
	}
	const openPhonePopubFlagFun=(fn=false,isOrtherNeedOpen=false,_tipConent="及时收到值日提醒")=>{
		tipConent.value = _tipConent
		//没有回调的弹窗，则代表是强关联的页面 、 有回调则代表不是强关联的页面，需要控制弹窗次数
		if(fn && !isOrtherNeedOpen && uni.getStorageSync('openPhoneNum')!==undefined && uni.getStorageSync('openPhoneNum') <=20){
			uni.setStorageSync('openPhoneNum',(uni.getStorageSync('openPhoneNum') || 0) + 1)
			return
		}else{
			uni.setStorageSync('openPhoneNum',0)
		}
		console.log('打卡打卡')
		bindPhoneCallback.value = fn
		openPhonePopubFlag.value = Math.random()
	}
	const goGetPrivacyInfo=()=>{
		wx.openPrivacyContract({})
	}
	//检查用户与隐私协议的状态
	const checkUserPrivacyProtocol=(callback)=>{
		if(wx.getPrivacySetting){
			wx.getPrivacySetting({
				success:res=>{
					console.log('隐私',res)
					protocolData.value.needAuthorization = res.needAuthorization ? Math.random() : -Math.random()
					if(res.needAuthorization){
						protocolData.value.callback = callback
						protocolData.value.title = res.privacyContractName
					}else{
						user_store.setUserInfo({
							...user_store.userInfo,
							isPrivacy:true
						})
						callback && callback()
						protocolData.value.callback = null
					}
				}
			})
		}
	}
	//点击同意隐私协议
	const handleAgreePrivacyAuthorization=()=>{
		protocolData.value.needAuthorization = -Math.random()
		user_store.setUserInfo({
			...user_store.userInfo,
			isPrivacy:true
		})
		nextTick(()=>{
			protocolData.value.callback && protocolData.value.callback()
			protocolData.value.callback = null
		})
	}
	//点击拒绝隐私协议
	const handleRefulePrivacy=()=>{
		user_store.setUserInfo({
			...user_store.userInfo,
			isPrivacy:false
		})
		protocolData.value.needAuthorization = -Math.random()
		uni.$emit('tips','拒绝后，平台将无法获取您的头像、微信昵称、选择的图片、手机号，可能会影响到您使用平台的相应功能','info',3000)
	}
	//创建插屏广告组件pushScreenAd
	const createPushScreenAd=()=>{
		const pushShowLastTime = uni.getStorageSync('pushShowLastTime')
		const formart='YYYY-MM-DD'
		if(pushShowLastTime === moment().format(formart)){
			console.log('不允许创建插屏广告')
			return
		}
		
		if(wx.createInterstitialAd){
		  pushScreenAd.value = wx.createInterstitialAd({ adUnitId: 'adunit-ab4aedfd646df784' })
		  pushScreenAd.value.onLoad(() => {
			console.log('插屏广告创建成功')
		  })
		  pushScreenAd.value.onError((err) => {
			console.log('插屏广告创建失败', err)
		  })
		  pushScreenAd.value.onClose((res) => {
			uni.$emit('tips','每天我(开发者)要付出40元的成本去维护这个平台，广告是我唯一的补贴来源哦','info',3000)
			
			if(!pushShowLastTime){
				uni.setStorageSync('pushShowLastTime',moment().format(formart))
			}else{
				//今天已经调用过了
				if(pushShowLastTime === moment().format(formart)){
					return
				}else{
					//不是今天
					uni.setStorageSync('pushShowLastTime',moment().format(formart))
				}
			}
		  })
		}
	}
	//弹出插屏广告
	const showPushScreenAd=()=>{
		if(pushScreenAd.value){
			pushScreenAd.value.show().catch(err=>{
				console.log('弹出插屏广告失败',err)
			})			
		}
	}
	//自动弹出插屏广告
	const autoShowPushScreenAd=()=>{
		setTimeout(()=>{
			showPushScreenAd()
		},2000)
	}
	//创建激励广告组件
	const createTaskVideoAd=()=>{
		taskVideoAd.value = null
		// 在页面onLoad回调事件中创建激励视频广告实例
		if (wx.createRewardedVideoAd) {
		  taskVideoAd.value = wx.createRewardedVideoAd({
		    adUnitId: 'adunit-5f7f25ffbe0a4329'
		  })
		  taskVideoAd.value.onLoad(() => {})
		  taskVideoAd.value.onError((err) => {
			  uni.$emit('tips','因第三方原因，请重试一下哦','error',1500)
			  uni.setStorageSync('taskVideoAdAndPageCatch',null)
		  })
		  taskVideoAd.value.onClose((res) => {
			  const {isEnded} = res
			  if(res && isEnded){
				  if(taskOkCallback.value){
					  taskOkCallback.value()
					  taskOkCallback.value=null
					  return
				  }
				  uni.$emit('tips','任务完成,请重新'+showIsViewAdTaskName.value,'success')
				  //完成观看
				  let taskVideoAdAndPageCatch=uni.getStorageSync('taskVideoAdAndPageCatch')
				  taskVideoAdAndPageCatch[nowPage.value].count = taskVideoAdAndPageCatch[nowPage.value].count+1
				  uni.setStorageSync('taskVideoAdAndPageCatch',taskVideoAdAndPageCatch)
			  }else{
				  taskOkCallback.value=null
				  uni.$emit('tips','没有看完哦，坚持下哦','info')
			  }
		  })
		}
	}
	
	//处理当前路由
	const handlePageByTaskVideoAd=()=>{
		const pages = getCurrentPages()
		nowPage.value = pages[pages.length-1]?.route
		if(!nowPage.value){
			return
		}
		console.log('当前页面',nowPage.value)
		const nowTime = moment().format('YYYY-MM-DD')
		let taskVideoAdAndPageCatch=uni.getStorageSync('taskVideoAdAndPageCatch')
		//有缓存
		if(taskVideoAdAndPageCatch){
			if(!taskVideoAdAndPageCatch[nowPage.value]){
				//缓存里没有当前页面
				taskVideoAdAndPageCatch[nowPage.value]={
					count:0,
					time:nowTime
				}
			}else{
				const lastTime = taskVideoAdAndPageCatch[nowPage.value]?.time
				//新的一天要重新开始计算该页面
				if(lastTime!==nowTime){
					taskVideoAdAndPageCatch=null
				}
			}
		}else{
			//没有缓存
			taskVideoAdAndPageCatch = {}
			taskVideoAdAndPageCatch[nowPage.value]={
				count:0,
				time:nowTime
			}
		}
		uni.setStorageSync('taskVideoAdAndPageCatch',taskVideoAdAndPageCatch)
	}
	
	const okViewAdVideoFun=()=>{
		// 用户触发广告后，显示激励视频广告
		if (taskVideoAd.value) {
		  taskVideoAd.value.show().catch(() => {
		    // 失败重试
		    taskVideoAd.value.load()
		      .then(() => taskVideoAd.value.show())
		      .catch(err => {
		        console.log('激励视频 广告显示失败')
		      })
		  })
		}else{
			uni.$emit('tips','请重新进入该页面后尝试','info',1500)
		}
	}
	const cancelViewAdVideoFun=()=>{
		uni.$emit('tips','每天我(开发者)要付出40元的成本去维护这个平台，广告是我唯一的补贴来源哦','info',3000)
		modelIsShowViewAdFlag.value = -Math.random()
	}
	
	//弹出是否观看激励广告
	const isViewTaskVideoAdFun=(task)=>{
		showIsViewAdTaskName.value = task
		modelIsShowViewAdFlag.value = Math.random()
	}
	
	//观看视频获取奖励
	const viewVideoGoTask=(callback)=>{
		taskOkCallback.value = callback
		okViewAdVideoFun()
	}
	
	onShow(()=>{
		console.log('测试挂在-挂')
		uni.$on('tips',tipsCallback)
		uni.$on('userStore',setUserStore)
		uni.$on('wxLogin',mpGetUserInfo)
		uni.$on('checkUserPrivacyProtocol',checkUserPrivacyProtocol)
		nextTick(()=>{
			uni.$on('openWXLoin',openWxLoginModelFun)
			uni.$on('openAuthMessageTip',openAuthMessageTipFun)
			uni.$on('openPhonePopubFlag',openPhonePopubFlagFun)
			uni.$on('openIsViewTaskVideoAd',isViewTaskVideoAdFun)
			uni.$on('viewVideoGoTask',viewVideoGoTask)
			uni.$on('showPushScreenAd',showPushScreenAd)
			uni.$on('getUserInfo',getUserInfo)
			uni.$on('autoShowPushScreenAd',autoShowPushScreenAd)
		})
		
		uni.getStorageSync('token') && !user_store?.userInfo.id && getUserInfo(true)
		uni.getStorageSync('newUserActive') && user_store?.userInfo.id && getUserInfo(true)
		handlePageByTaskVideoAd()
	})
	onHide(()=>{
		console.log('测试挂在-卸',0)
		uni.$off('tips',tipsCallback)
		uni.$off('userStore',setUserStore)
		uni.$off('wxLogin',mpGetUserInfo)
		uni.$off('openWXLoin',openWxLoginModelFun)
		uni.$off('openAuthMessageTip',openAuthMessageTipFun)
		uni.$off('openPhonePopubFlag',openPhonePopubFlagFun)
		uni.$off('openIsViewTaskVideoAd',isViewTaskVideoAdFun)
		uni.$off('viewVideoGoTask',viewVideoGoTask)
		uni.$off('showPushScreenAd',showPushScreenAd)
		uni.$off('checkUserPrivacyProtocol',checkUserPrivacyProtocol)
		uni.$off('autoShowPushScreenAd',autoShowPushScreenAd)
		uni.$off('getUserInfo',getUserInfo)
		protocolData.value.callback = null
	})
	onLoad(()=>{
		createTaskVideoAd()
		createPushScreenAd()
	})
</script>

<style lang="less">
.btn_box_solt{
	width: 100%;
	display: flex;
	justify-content: space-between;
}
.get_key_phone{
		margin: 0 !important;
		width: 45%;
		height: 100rpx;
		background-color: v-bind(primary_cool_color) !important;
		border: 0rpx solid v-bind(primary_cool_color) !important;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF !important;
	}
.get_key_phone:hover {
   background-color: #FFFFFF !important;
   color:v-bind(primary_text_color) !important;
   border: 1rpx solid v-bind(primary_cool_color) !important;
}
.get_key_phone_cancel{
	background-color: v-bind(primary_text_color) !important;
	border: 0rpx solid v-bind(primary_text_color) !important;
}
.get_key_phone_cancel:hover {
   background-color: #FFFFFF !important;
   color:v-bind(primary_text_color) !important;
   border: 1rpx solid v-bind(primary_hot_color) !important;
}
.protocol_box{
	color: v-bind(primary_text_color);
	font-size: 32rpx;
	text-indent: 2em;
	.protocol_name_url{
		color: v-bind(primary_cool_color);
	}
}
.protocol_cancel{
	margin: 0 !important;
	width: 45%;
	height: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	color: v-bind(primary_cool_color) !important;
	font-size: 34rpx;
	background-color: rgb(236,238,245) !important;
	border: 1px solid rgb(236,238,245) !important;
}
</style>